package util.thread_pool;

import exception.UnifiedExceptionConsole;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.scene.control.Alert;
import javafx.scene.control.TextArea;
import model.CpdetectorUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.Common;

import java.io.*;

public class GetFileContentTask extends Task<Void> {

    /**
     * 任务名称
     */
    private final String name;

    private final static Logger logger = LoggerFactory.getLogger(GetFileContentTask.class);

    private final TextArea displayTextArea;

    private final File f;

    private final long handledisplayBufferUpperLimit;

    /**
     * 构造函数
     *
     */
    public GetFileContentTask(String name, TextArea displayTextArea, long handledisplayBufferUpperLimit, File f) {
        this.name = name;
        this.displayTextArea = displayTextArea;
        this.handledisplayBufferUpperLimit = handledisplayBufferUpperLimit;
        this.f = f;
    }

    @Override
    protected Void call() throws Exception {

        /*
              此处的读取文件编码格式只是为了解决显示汉字乱码的问题
             */
        String charsetName = CpdetectorUtils.getFileCharset(f.getAbsolutePath());
        logger.info("Open File CharsetName: {}", charsetName);

        Platform.runLater(() -> {
            //文件内容的读取
            //InputStreamReader类是从字节流到字符流的桥接器：它使用指定的字符集读取字节并将它们解码为字符。
            InputStreamReader reader = null;
            try {
                reader = new InputStreamReader(new FileInputStream(f), charsetName);
            } catch (Exception e) {
                UnifiedExceptionConsole.console(e);
            }

            if (reader == null) {
                Common.alert(Alert.AlertType.WARNING, "警告", "打开的文件为空文件！");
                return;
            }
            //BufferedReader类从字符输入流中读取文本并缓冲字符，以便有效地读取字符，数组和行
            BufferedReader bfreader = new BufferedReader(reader);

            /*if (f.length() > handledisplayBufferUpperLimit) {
                alert(Alert.AlertType.WARNING, "警告", "文件大小超过显示区缓冲上限");
                return;
            }*/
            displayTextArea.setText("文件大小: " + f.length() + " 字节，下面是预览的前 " + 10 + " 行内容：\n");
            //缓冲BufferedReader读取的每一行字符
            String line;
            //包含该行内容的字符串，不包含任何行终止符，如果已到达流末尾，则返回 null
            try {
                int i = 10;
                while (((line = bfreader.readLine()) != null) && (i-- > 0)) {
                    if (displayTextArea.getText().length() < handledisplayBufferUpperLimit) {
                        displayTextArea.appendText(line + "\n");
                    } else {
                        displayTextArea.appendText("已达显示区缓冲上限！\n");
                        break;
                    }
                }
            } catch (IOException e) {
                logger.error("Exception", e);
            }

            try {
                //关闭InputStreamReader
                reader.close();
                //关闭BufferedReader
                bfreader.close();
            } catch (IOException ex) {
                logger.error("IOException", ex);
            }
        });

        return null;
    }

    @Override
    protected void succeeded() {
        super.succeeded();
        updateMessage("Done!");
        logger.info("{} is Done!", this);
    }

    @Override
    protected void cancelled() {
        super.cancelled();
        updateMessage("Cancelled!");
        logger.info("{} is Cancelled!", this);
    }

    @Override
    protected void failed() {
        super.failed();
        updateMessage("Failed!");
        logger.info("{} is Failed!", this);
    }

    @Override
    protected void running() {
        super.running();
        updateMessage("Running!");
        logger.info("{} is Running!", this);
    }

    @Override
    protected void scheduled() {
        super.scheduled();
        updateMessage("Scheduled!");
        logger.info("{} is Scheduled!", this);
    }

    /**
     * 获取任务名称
     *
     * @return 任务名称
     */
    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "GetFileContentTask [ name = " + name + " ]";
    }
}
